/**
 * 会话API模块
 * 负责处理会话相关的API调用
 */

class SessionAPI {
  constructor() {
    this.config = null;
    this.init();
  }

  /**
   * 初始化配置
   */
  async init() {
    try {
      const response = await fetch('./config.json');
      this.config = await response.json();
    } catch (error) {
      console.error('加载配置失败:', error);
    }
  }

  /**
   * 获取会话列表
   * @param {string} userId - 用户ID
   * @returns {Promise<Array>} 会话列表
   */
  async getSessions(userId) {
    if (!this.config) {
      await this.init();
    }

    try {
      const apiUrl = `${this.config.ollama.OLLAMA_BASE_URL}${this.config.ollama.api.sessions}?userId=${userId}`;
      
      const response = await fetch(apiUrl, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
        timeout: this.config.backend.timeout || 30000
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const data = await response.json();
      return data;
    } catch (error) {
      console.error('获取会话列表失败:', error);
      
      // 返回模拟数据用于测试
      if (error.message.includes('fetch')) {
        console.log('API不可用，返回模拟数据');
        return this.getMockSessions();
      }
      
      throw error;
    }
  }

  /**
   * 获取模拟会话数据（用于测试）
   */
  getMockSessions() {
    return [
      {
        sessionId: "session_001",
        sessionName: "技术讨论 - React开发"
      },
      {
        sessionId: "session_002", 
        sessionName: "产品需求分析"
      },
      {
        sessionId: "session_003",
        sessionName: "代码优化方案"
      },
      {
        sessionId: "session_004",
        sessionName: "架构设计讨论"
      },
      {
        sessionId: "session_005",
        sessionName: "Bug修复计划"
      }
    ];
  }

  /**
   * 创建新会话
   * @param {string} userId - 用户ID
   * @param {string} sessionName - 会话名称
   * @returns {Promise<Object>} 创建的会话信息
   */
  async createSession(userId, sessionName) {
    if (!this.config) {
      await this.init();
    }

    try {
      const apiUrl = `${this.config.ollama.OLLAMA_BASE_URL}${this.config.ollama.api.sessions}`;
      
      const response = await fetch(apiUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          userId: userId,
          sessionName: sessionName
        }),
        timeout: this.config.backend.timeout || 30000
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const data = await response.json();
      return data;
    } catch (error) {
      console.error('创建会话失败:', error);
      throw error;
    }
  }

  /**
   * 删除会话
   * @param {string} sessionId - 会话ID
   * @returns {Promise<boolean>} 删除是否成功
   */
  async deleteSession(sessionId) {
    if (!this.config) {
      await this.init();
    }

    try {
      const apiUrl = `${this.config.ollama.OLLAMA_BASE_URL}${this.config.ollama.api.sessions}/${sessionId}`;
      
      const response = await fetch(apiUrl, {
        method: 'DELETE',
        headers: {
          'Content-Type': 'application/json',
        },
        timeout: this.config.backend.timeout || 30000
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      return true;
    } catch (error) {
      console.error('删除会话失败:', error);
      throw error;
    }
  }
}

// 导出API类
window.SessionAPI = SessionAPI;
